package com.bruce.tool.map.gaode.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bruce.tool.map.gaode.web.config.GaodeConfig;
import com.bruce.tool.map.gaode.web.constant.MapApiConstant;
import com.bruce.tool.map.gaode.web.to.Address;
import com.bruce.tool.map.gaode.web.to.AddressResult;
import com.bruce.tool.map.gaode.web.to.PointResult;
import com.bruce.tool.map.gaode.web.to.Point;
import com.bruce.tool.rpc.http.core.Https;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * @author 刘正航
 * @version 2021/3/21
 */
@Component
public class GaodeTranslateHandler {
    @Autowired
    private GaodeConfig gaodeConfig;

    public Point translate(String address) {
        // address=北京市朝阳区阜通东大街6号&output=XML&key=<用户的key>
        String resultInfo = Https.create().url(MapApiConstant.ADDRESS_TO_POINT_URL)
                .add("address", address)
                .add("output", "json")
                .add("key", gaodeConfig.getKey())
                .get();
        PointResult result = JSON.parseObject(resultInfo, PointResult.class);
        return Optional.ofNullable(result)
                .map(item -> {
                    if (!CollectionUtils.isEmpty(item.getGeocodes())) {
                        return item.getGeocodes().get(0);
                    } else {
                        return null;
                    }
                })
                .map(PointResult.ResultInfo::getLocation)
                .orElse(null);
    }

    public Address translate(Point point) {
        String resultInfo = Https.create().url(MapApiConstant.POINT_TO_ADDRESS_URL)
                .add("location", point.toLocation())
                .add("extensions", "base")
                .add("batch", "false")
                .add("roadlevel", "1")
                .add("output", "json")
                .add("key", gaodeConfig.getKey())
                .get();
        AddressResult result = JSON.parseObject(resultInfo, new TypeReference<AddressResult>() {
        });
        Address address = Optional.ofNullable(result)
                .map(AddressResult::getRegeocode)
                .map(AddressResult.Regeocode::getAddressComponent)
                .map(item2 -> Address.builder()
                        .province(item2.getProvince())
                        .city(item2.getCity())
                        .district(item2.getDistrict())
                        .build())
                .orElse(null);
        if (Objects.nonNull(address)) {
            if ("[]".equals(address.getCity()) && StringUtils.isNotBlank(address.getDistrict())) {
                address.setCity(address.getProvince());
            }
        }
        return address;
    }
}
